package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    private final IUserService userService;
    private final StringRedisTemplate stringRedisTemplate;
    private final IFollowService followService;


    private static final String BLOG_LIKED_KEY = "blog:liked:";
    private static final String FEED_KEY = "feed:";

    /**
     * 查询博客详情
     *
     * @param id
     * @return
     */
    @Override
    public Blog queryBlogById(Long id) {
        Blog blog = this.getById(id);
        if (blog == null) {
            throw new RuntimeException("博客不存在");
        }
        fillUsers(blog);
        return blog;
    }

    @Override
    public List<Blog> queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        fillUsers(records);
        return records;
    }

    /**
     * 查询博客点赞数
     *
     * @param id
     * @return
     */
    @Override
    public List<UserDTO> querylikeBlog(Long id) {
        // 博客最先点赞的人数
        String key = BLOG_LIKED_KEY + id;

        Set<String> userIds = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (CollUtil.isEmpty(userIds)) {
            // 没有数据:返回空集合
            return Collections.emptyList();
        }
        StringJoiner sj = new StringJoiner(",");
        userIds.forEach(sj::add);

        List<Long> idList = userIds.stream().map(Long::valueOf).collect(Collectors.toList());
        List<User> users = userService.query().in("id", idList).last("ORDER BY FIELD(id," + sj + ")").list();
        //判空
        if (CollUtil.isEmpty(users)) return Collections.emptyList();
        //转dto
        return users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
    }

    /**
     * 点赞/取消点赞
     *
     * @param id
     */
    @Override
    public void likeBlog(Long id) {
        //1. 获取当前用户
        String userId = UserHolder.getUser().getId().toString();
        //2. 查询redis中的数据
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        //3.判断是否已经点赞过
        if (score == null) {
            //4.如果没有点赞,新增点赞
            boolean success = update().setSql("liked = liked + 1").eq("id", id).update();
            if (success) {
                stringRedisTemplate.opsForZSet().add(key, userId, System.currentTimeMillis());
            }
        } else {
            //5.如果已经点赞,取消
            boolean success = update().setSql("liked = liked - 1").eq("id", id).update();
            if (success) {
                stringRedisTemplate.opsForZSet().remove(key, userId);
            }
        }
    }

    /**
     * 保存博客
     *
     * @param blog
     * @return
     */
    @Override
    public Long savBlog(Blog blog) {

        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) return -1L;
        // 获取博客id
        Long blogId = blog.getId();
        // 推送至关注者
        List<Follow> followIds = followService.query().select("user_id").eq("follow_user_id", user.getId()).list();
        if (CollUtil.isNotEmpty(followIds)) {
            List<Long> userIds = followIds.stream().map(Follow::getUserId).collect(Collectors.toList());
            for (Long userId : userIds) {
                String key = FEED_KEY + userId;
                stringRedisTemplate.opsForZSet().add(key, blogId.toString(), System.currentTimeMillis());
            }
        }
        return blogId;
    }

    /**
     * 滚动查询博客
     */
    @Override
    public ScrollResult queryBlogOfFollow(Long max, Integer offset) {

        // 获取用户id
        Long userId = UserHolder.getUser().getId();
        String key = FEED_KEY + userId;
        // 查询redis
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (CollUtil.isEmpty(typedTuples)) return new ScrollResult();
        Long minTime = 0L;
        int offsetFinal = 1;
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            // 博客id
            String value = tuple.getValue();
            // 发布时间
            Double score = tuple.getScore();
            if (StrUtil.isNotBlank(value) && value != null) {
                blogIds.add(Long.valueOf(value));
            }
            if (score != null) {
                if (minTime != score.longValue()) {
                    // 如果不相等,就向下顺延
                    minTime = score.longValue();
                    // 重置offset
                    offsetFinal = 1;
                } else {
                    // 相等,就将offset+1
                    offsetFinal++;
                }
            }
        }
        // 转为有序字符串
        String idStr = StrUtil.join(",", blogIds);
        List<Blog> blogs = query().in("id", blogIds).last("ORDER BY FIELD(id," + idStr + ")").list();
        // 填充用户信息
        fillUsers( blogs);
        ScrollResult sr = new ScrollResult();
        sr.setList(blogs);
        sr.setOffset(offsetFinal);
        sr.setMinTime(minTime);

        return sr;
    }

    /**
     * 填充用户信息
     *
     * @param records
     */
    private void fillUsers(List<Blog> records) {
        Set<Long> userIds = records.stream()
                .map(Blog::getUserId).collect(Collectors.toSet());
        //   批量查询信息
        List<User> users = userService.listByIds(userIds);
        Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));

        // 填充用户信息
        for (Blog blog : records) {
            Long userId = blog.getUserId();
            User user = userMap.get(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());

            UserDTO loginUser = UserHolder.getUser();
            if (loginUser != null) {
                Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + blog.getId(), loginUser.getId().toString());
                blog.setIsLike(score != null);
            }
        }
    }

    /**
     * 填充用户信息
     *
     * @param blog
     */
    private void fillUsers(Blog blog) {
        User user = userService.getById(blog.getUserId());
        // 填充用户信息
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        UserDTO loginUser = UserHolder.getUser();
        if (loginUser != null) {
            Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + blog.getId(), loginUser.getId().toString());
            blog.setIsLike(score != null);
        }
    }
}
